package com.lvhx.springboot.sofarpc;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.lvhx.facade.HelloService;
import com.lvhx.facade.dto.HelloRequest;
import com.lvhx.facade.dto.HelloResponse;
import com.lvhx.springboot.base.*;
import com.lvhx.springboot.callservice.BaseAction;
import com.lvhx.springboot.dynamicdatasource.DataSource;
import com.lvhx.springboot.entity.batch.Acctbal;
import com.lvhx.springboot.mapper.batch.AcctbalMapper;
import com.lvhx.springboot.mapper.extend.UserExtendMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auther 吕宏旭
 * @date 2020/6/7 10:33
 */
@DataSource("master")
public class HelloServiceImpl extends BaseAction implements HelloService {
    private Repository<AccountAggregateUser> repository;

    public void setRepository(Repository<AccountAggregateUser> repository) {
        this.repository = repository;
    }

    Logger logger = LoggerFactory.getLogger(HelloServiceImpl.class);
    @Resource
    private UserExtendMapper userExtendMapper;
    @Resource
    private AcctbalMapper acctbalMapper;

    @Autowired
    private TransactionManager transactionManager;

    /**
     * 使用工作单元控制事务提交和回滚
     *
     * @param request
     * @return
     */
    @Override
    public HelloResponse hello(HelloRequest request) {
        MDC.put("CBID", getCurrentDate8() + "/online/traceLog");
        logger.info("=====hello入参为：{}", JSON.toJSONString(request));

        UnitOfWorkFactory unitOfWorkFactory = new DefaultUnitOfWorkFactory();
        UnitOfWork unitOfWork = unitOfWorkFactory.createUnitOfWork(transactionManager);

        HelloResponse response = null;
        try {
            // 测试事务
            Acctbal acctbal = acctbalMapper.selectByPrimaryKey("18913000000");
            acctbal.setAmt(acctbal.getAmt().add(new java.math.BigDecimal(1)));
            acctbalMapper.updateByPrimaryKeySelective(acctbal);


            //　测试聚合根
            AccountAggregateUser account = repository.load(1L);
            account.setName(IdUtil.simpleUUID());
            account.setSalt(IdUtil.simpleUUID());
            account.setEmail(IdUtil.simpleUUID());

//            int i = 1 / 0;

            response = new HelloResponse();
            response.setMessage("finished");
            response.setValue("response son");

        } catch (Exception e) {
            unitOfWork.rollback(e);
            throw new RuntimeException(e);
        }

        unitOfWork.commit();

        return response;
    }

    public String getCurrentDate8() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        return format.format(new Date());
    }

}
